//
//  RITLQRCodeMaker.m
//  QDMetroClient
//
//  Created by YueWen on 2018/12/28.
//  Copyright © 2018 YueWen. All rights reserved.
//

#import "RITLQRCodeMaker.h"

@implementation RITLQRCodeMaker

+ (UIImage *)makeQRCodeWithValue:(NSString *)value size:(CGFloat)size {
    
    //转成二进制数据
    NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];

    return [self makeQRCodeWithData:data size:size];
}



+ (nullable UIImage *)makeQRCodeWithData:(NSData *)data size:(CGFloat)size {
    
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    if (!filter) { return nil; }//过滤器创建失败
    
    //还原滤镜默认设置
    [filter setDefaults];
    [filter setValue:data forKey:@"InputMessage"];
    
    CIImage *image = filter.outputImage;
    if (!image) { return nil; }
    
    return [self createHightDefinitionQRCodeWithImage:image size:size];
}


/// 创建高清的二维码
+ (UIImage *)createHightDefinitionQRCodeWithImage:(CIImage *)image size:(CGFloat)size {
    
    //获得图片最小的矩形范围
    CGRect extentRect = CGRectIntegral(image.extent);
    
    //获得比例
    CGFloat scale = MIN(size / CGRectGetWidth(extentRect), size / CGRectGetHeight(extentRect));
    
    //创建bitmap
    size_t width = CGRectGetWidth(extentRect) * scale;
    size_t height = CGRectGetHeight(extentRect) * scale;
    
    //创建灰度Ref
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    //创建map,使用RGB渲染
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    //创建CI环境
    CIContext *context = [CIContext contextWithOptions:nil];
    
    //进行处理
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extentRect];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extentRect, bitmapImage);
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

@end
